package com.skytech.component.monitor.enterprise_data_monitoring;


import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.data.MonitorDataDAO;
import com.skytech.component.monitor.data.MonitorDataTag;
import com.skytech.component.monitor.data.MonitorDataTagDAO;
import com.skytech.component.monitor.util.FormateConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class QingHaiService implements CrawlerScript {
    private static final String province = "青海";

    private static final Logger log = LoggerFactory.getLogger(QingHaiService.class);

    @Autowired
    private MonitorDataTagDAO monitorDataTagDAO;
    @Autowired
    private MonitorDataDAO monitorDataDAO;

    @Override
    public void start() {

        String url = "http://125.72.26.66:8888/enterprisemonitor/gisnavigation!companylist.action";
        String date = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Document document = null;
        List<String> entIds = new ArrayList<>();
        try {

            document = FormateConnection.createConnection(Jsoup.connect(url))
                    .get();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        Elements allElements = document.getAllElements();
        allElements.select("body > div > li a").forEach(l -> {
            String id = l.attr("onclick");
            if (!StringUtils.isEmpty(id)) {
                entIds.add(id.split("'")[1]);
            }
        });

        MonitorData monitorData;
        List<MonitorData> monitorDataList;
        int j = 0;
    //    WebClient webClient = getWebClient();
        for (String entId : entIds) {
            log.info("{}企业开始", entId);
            /*   try{*/
            // 企业基本信息
            String entInfo = "http://125.72.26.66:8888/enterprisemonitor/enterprise-info!getCompanyInfo.action?companyid=" + entId;
            //  HtmlPage page;
            try {
                //page = webClient.getPage(entInfo);
                document = FormateConnection.createConnection(Jsoup.connect(entInfo))
                        .get();
                /*webClient.closeAllWindows();*/
            } catch (Exception e) {
                log.error("企业{},发生错误{}", entId, e.getMessage());
                continue;
            }
            //Elements allElement = document.getAllElements();
            //Document parse = Jsoup.parse(page.getBody().asXml());
            Elements ele = document.getElementsMatchingOwnText("企业名称");
            String entName = ele.next().text();
            ele = document.getElementsMatchingOwnText("企业地址");
            String address = ele.next().text();

            String water = "http://125.72.26.66:8888/enterprisemonitor/enterprise-info!getWasteWaterLists.action?companyid=" + entId + "&yesterday=" + date;
            //webClient = getWebClient();
            try {
                // page = webClient.getPage(water);
                document = FormateConnection.createConnection(Jsoup.connect(water))
                        .get();
                /*webClient.closeAllWindows();*/
            } catch (Exception e) {
                log.error("企业{},发生错误{}", entId, e.getMessage());
                continue;
            }
            //parse = Jsoup.parse(page.getBody().asXml());
            Elements elements = document.getAllElements();

            ele = elements.select("body > table > tbody tr:nth-child(n+2)");
            monitorDataList = new ArrayList<>();
            // Collections.reverse(ele);
            String waterUniqueKey = entName + "--" + "water";
            MonitorDataTag monitorDataTag = new MonitorDataTag();
            monitorDataTag.setProvince(province);
            monitorDataTag.setUniqueKey(waterUniqueKey);
            List<MonitorDataTag> waterHistory = monitorDataTagDAO.findAll(Example.of(monitorDataTag));
            if (!ele.isEmpty()) {
                for (int i = 0; i < ele.size(); i++) {
                    //todo parse
                    Elements tds = ele.get(i).getElementsByTag("td");
                    if (tds.size() <=7) {
                       // System.out.println(tds);
                        continue;
                    }
                    monitorData = new MonitorData();
                    monitorData.setId(UUID.randomUUID().toString())
                            .setCompanyName(entName)
                            .setAddress(address)
                            .setProvince(province)
                            .setMonitorPoint(tds.get(0).attr("title"))
                            .setMonitorInfo(tds.get(4).attr("title"))
                            .setMonitorValue(tds.get(5).text())
                            .setMonitorTime(tds.get(2).attr("title"))
                            .setMonitorType(tds.get(3).attr("title"))
                            .setMonitorStandardValue(tds.get(6).attr("title"))
                            .setOverproof(tds.get(7).text())
                            .setPollutionType("废水")
                            .setMonitorRate(tds.get(1).text());
                    monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    if (monitorDataDAO.findAll(Example.of(monitorData)).isEmpty()) {
                        monitorDataList.add(monitorData);
                    }


                }
            }
            saveData(monitorDataList, waterHistory, waterUniqueKey);


            //todo 解析废水信息
            monitorDataList = new ArrayList<>();
            //废气体
            String air = "http://125.72.26.66:8888/enterprisemonitor/enterprise-info!getWasteAirLists.action?companyid=" + entId + "&yesterday=" + date;


            /* webClient = getWebClient();*/
            //webClient.addRequestHeader("Referer", "http://nmgepb.gov.cn:8088/enterprisemonitor/gisnavigation!cityCompanyList.action");
            try {
                document = FormateConnection.createConnection(Jsoup.connect(air))
                        .get();

                //   page = webClient.getPage(air);
                /*webClient.closeAllWindows();*/
            } catch (Exception e) {
                log.error("企业{},发生错误{}", entId, e.getMessage());
                continue;
            }
            //parse = Jsoup.parse(page.getBody().asXml());
            elements = document.getAllElements();

            ele = elements.select("body > table > tbody tr:nth-child(n+2)");
            //Collections.reverse(ele);
            String gasUniqueKey = entName + "--" + "gas";
            monitorDataTag = new MonitorDataTag();
            monitorDataTag.setProvince(province);
            monitorDataTag.setUniqueKey(gasUniqueKey);
            List<MonitorDataTag> gasHistory = monitorDataTagDAO.findAll(Example.of(monitorDataTag));
            if (!ele.isEmpty()) {
                for (int i = 0; i < ele.size(); i++) {

                    //todo parse
                    Elements tds = ele.get(i).getElementsByTag("td");
                    if (tds.size() <= 7) {
                        continue;
                    }
                    monitorData = new MonitorData();
                    monitorData.setId(UUID.randomUUID().toString())
                            .setCompanyName(entName)
                            .setAddress(address)
                            .setProvince(province)
                            .setMonitorPoint(tds.get(0).attr("title"))
                            .setMonitorInfo(tds.get(4).attr("title"))
                            .setMonitorValue(tds.get(5).text())
                            .setMonitorTime(tds.get(2).attr("title"))
                            .setMonitorType(tds.get(3).attr("title"))
                            .setMonitorStandardValue(tds.get(6).attr("title"))
                            .setOverproof(tds.get(7).text())
                            .setPollutionType("废气")
                            .setMonitorRate(tds.get(1).text());
                    monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    monitorDataList.add(monitorData);

                }
            }
            saveData(monitorDataList, gasHistory, gasUniqueKey);


            //todo 解析废气信息
            monitorDataList = new ArrayList<>();
            //
            //噪声
            String noise = "http://125.72.26.66:8888/enterprisemonitor/enterprise-info!getNoiseLists.action?companyid=" + entId + "&yesterday=" + date;
            /*webClient = getWebClient();*/
            // webClient.addRequestHeader("Referer", "http://nmgepb.gov.cn:8088/enterprisemonitor/gisnavigation!cityCompanyList.action");
            try {
                document = FormateConnection.createConnection(Jsoup.connect(noise))
                        .get();
                //page = webClient.getPage(noise);
                /*webClient.closeAllWindows();*/
            } catch (Exception e) {
                log.error("企业{},发生错误{}", entId, e.getMessage());
                continue;
            }
            // parse = Jsoup.parse(page.getBody().asXml());
            elements = document.getAllElements();

            ele = elements.select("body > table > tbody tr:nth-child(n+2)");
            //Collections.reverse(ele);
            String noiseUniqueKey = entName + "--" + "noise";
            monitorDataTag = new MonitorDataTag();
            monitorDataTag.setProvince(province);
            monitorDataTag.setUniqueKey(noiseUniqueKey);
            List<MonitorDataTag> noiseHistory = monitorDataTagDAO.findAll(Example.of(monitorDataTag));
            if (!ele.isEmpty()) {
                for (int i = 0; i < ele.size(); i++) {
                    //todo parse
                    Elements tds = ele.get(i).getElementsByTag("td");
                    if (tds.size() < 6) {
                        continue;
                    }
                    monitorData = new MonitorData();
                    monitorData.setId(UUID.randomUUID().toString())
                            .setCompanyName(entName)
                            .setAddress(address)
                            .setProvince(province)
                            .setMonitorPoint(tds.get(0).attr("title"))
                            .setMonitorInfo(tds.get(2).attr("title"))
                            .setMonitorValue(tds.get(3).attr("title"))
                            .setMonitorTime(tds.get(1).attr("title"))
                            .setMonitorType("自动监测")
                            .setMonitorStandardValue(tds.get(4).attr("title"))
                            .setOverproof(tds.get(5).attr("title"))
                            .setPollutionType("噪声");
                    monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    monitorDataList.add(monitorData);

                }
            }
            saveData(monitorDataList, noiseHistory, noiseUniqueKey);
            j++;
        }
        log.info("总共完成{}条企业数据抓取", j);
    }

    private void saveData(List<MonitorData> monitorDataList, List<MonitorDataTag> monitorDataTagList, String uniqueKey) {

        if (!monitorDataList.isEmpty()) {
            if (monitorDataTagList.isEmpty()) {
                MonitorDataTag monitorDataTag = new MonitorDataTag();
                monitorDataTag.setId(UUID.randomUUID().toString());
                monitorDataTag.setProvince(province);
                monitorDataTag.setUniqueKey(uniqueKey);
                monitorDataTag.setLabel(monitorDataList.get(0).getMonitorPoint() + monitorDataList.get(0).getMonitorTime());
                monitorDataTagDAO.save(monitorDataTag);
                monitorDataDAO.saveAll(monitorDataList);
            } else {
                int k = 0;
                for (MonitorData data : monitorDataList) {
                    if (monitorDataTagList.get(0).getLabel().equals(data.getMonitorPoint() + data.getMonitorTime())) {
                        break;
                    } else {
                        monitorDataDAO.save(data);
                        if (k == 0) {
                            MonitorDataTag monitorDataTagUpdate = monitorDataTagList.get(0);
                            monitorDataTagUpdate.setLabel(data.getMonitorPoint() + data.getMonitorTime());
                            monitorDataTagDAO.save(monitorDataTagUpdate);
                        }
                        k++;
                    }
                }
            }
            monitorDataTagList.clear();
            monitorDataList.clear();
        }
    }
}
